import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2020/6/30.
 */
import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import errorMessage from 'share/errorMessage'
import baseService from 'share/base.service'
import requestService from 'containers/request/request.service'
import approveRequestService from 'containers/approve/request/request.service'
import travelService from 'containers/request/travel-request/travel.service'
import { message, Form, Spin, Button, Affix,  Modal } from 'antd'
const FormItem = Form.Item;
import travelUtil from 'containers/request/travel-request/travelUtil'
import requestUtil from 'containers/request/slide/request-util'
import moment from 'moment'
import WaterMark from 'components/water-mark'
import 'styles/request/new-request.scss'
import customField from 'share/customField'
import chooserData from 'share/chooserData'
import Chooser from 'components/chooser'
const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 14, offset: 1},
};

class RequestEditContent extends React.Component{
  isSetCloseEnabled = false;//是否设置了停用日期
  closeDate = "";//预计停用日期
  closeDay = 0; //差旅结束后多少天自动停用
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      saveLoading: false,
      formInfo: {}, //表单详情
      info: {}, //单据详情
      jobId: '', //单据岗位id
      jobInfo: {}, //岗位信息
      isShowRangePicker: false, //是否展示日期连选
      formDefaultValue: [], //表单默认值
      copyDefaultValues: [],
      signEnable: false, //是否可以加签
      signCompanyOIDs:[],//加签人公司范围
      itineraryHeadList: [], //行程相关信息
      isAlreadyClearSubsidy: false, //是否已经清空过差补
      isAlreadyClearBudgetDetail: false, //是否已经清空过预算明细
      quotaObj: {}, //申请额度信息
    };
    this.requestEdit = menuRoute.getRouteItem('request-edit-v2','key'); //申请单编辑页
  }

  componentWillMount(){}

  componentDidMount(){
    const { params } = this.props;
    if (params.jobInfo) {
      this.setState({jobId: params.jobInfo.id, jobInfo: params.jobInfo});
    }
    this.setState({
      formInfo: JSON.parse(JSON.stringify(params.formInfo)),
      quotaObj: JSON.parse(JSON.stringify(params.quotaObj))
    });
    this.isCounterSignEnable();
    this.initInfo();
    this.getItineraryHead();
  }

  componentWillReceiveProps() {
    const { formInfo } = this.state;
    let values = this.props.form.getFieldsValue();
    //更新formInfo下的customFormFields
    let cust = this.getCustFormValues(values) || [];
    cust.forEach((item, index) => {
      if (item.messageKey === 'select_participant') {
        let baseStartData = this.state.copyDefaultValues[index];
        if (travelUtil.checkIsArrayChange(baseStartData.value, item.value, 'userOID', true)
          && requestUtil.isHasSubsidy(this.state.itineraryHeadList) && !this.state.isAlreadyClearSubsidy) {
          //有差补且参与人改变
          let currentKey = item.formValueOID;
          this.baseModalShow(messages('request-1.key230')/*更改参与人将影响差补计算结果，是否清空差补？*/, baseStartData, currentKey, index, item);
        }
      }
      if (item.messageKey === 'cust_list') {
        let baseStartData = this.state.copyDefaultValues[index];
        let isSubsidyRelated = false; //是否是差补相关的值列表控件
        let maps = formInfo.customFormPropertyMap;
        let subsidyDimension = maps['travel.subsidies.dimension'] ? JSON.parse(maps['travel.subsidies.dimension']) : false;
        if(subsidyDimension && subsidyDimension.formFieldOIDs && subsidyDimension.formFieldOIDs.indexOf(item.fieldOID) > -1) {
          isSubsidyRelated = true;
        }
        if (isSubsidyRelated && baseStartData.value !== item.value
          && requestUtil.isHasSubsidy(this.state.itineraryHeadList) && !this.state.isAlreadyClearSubsidy) {
          let currentKey = item.formValueOID;
          this.baseModalShow(messages('request-1.key229',{arg1: item.fieldName})/*更改{arg1}将清空已添加差补*/, baseStartData, currentKey, index, item);
        }
      }
    });
  };

  baseModalShow = (message, data, currentKey, index, newField) => {
    Modal.confirm({
      title: messages('common.info')/*提示*/,
      content: <div>
        <p>{message}</p>
      </div>,
      okText: messages('request-1.key420')/*更改*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: ()=> {
        this.clearSubsidy();
        //更新副本中的默认值
        this.updateCopyDefaultValue(index, newField);
      },
      onCancel: ()=> {
        let setData = {};
        let info = this.state.info;
        info.custFormValues.forEach((custFormValue, custIndex) => {
          if (custIndex === index && custFormValue.messageKey === 'select_participant') {
            custFormValue.value = data.value;
            setData[currentKey] = JSON.parse(data.value || '[]');
          }
          if (custIndex === index && custFormValue.messageKey === 'cust_list') {
            custFormValue.value = data.value;
            setData[currentKey] = customField.getDefaultValue(data, data.initValue);
          }
        });
        this.props.form.setFieldsValue(setData);
        this.setState({info});
      },
    });
  };

  //更新复制默认值
  updateCopyDefaultValue = (index, newField) => {
    let copy = this.state.copyDefaultValues;
    copy.map(res => {
      // 修改值列表时候需要进一步判断formValueOID，因为所有的值列表messageKey都是cust_list
      if(res.messageKey === newField.messageKey && res.formValueOID === newField.formValueOID){
        res.value = newField.value;
      }
    });
    this.setState({copyDefaultValues: copy});
  };

  //获取保存、提交申请单时的custFormValues
  //isClearRange是否要去除连选控件
  getCustFormValues = (values, isClearRange) => {
    let custFormValues = null;
    if (isClearRange) {
      //提交／保存前是不需要对象引用的，深拷贝一份做为传给后台的数据，如果接口出错了，也不影响原有的数据
      custFormValues = JSON.parse(JSON.stringify(this.state.info.custFormValues));
    } else {
      //非提交／保存时需要对象引用，这样一些控件的绑定关系不会断
      custFormValues = this.state.info.custFormValues;
    }

    if (!custFormValues) {
      return;
    }

    custFormValues.map(item=> {
      Object.keys(values).map(key => {
        //bugfix 48644 内部参与人控件配置了隐藏，但是在新建差旅单保存跳到另一个页面状态之间，竟然获取到了内部参与人控件以fieldOID为formItem key的value值，
        //因为渲染处隐藏了，就没有执行getInitialValue，而导致内部参与人被清空了，我就不明白了，怎么隐藏了，获取form的value还能获取到这个
        //先处理成隐藏了的就不执行formatFormValue
        if ((key === item.fieldOID || key === item.formValueOID) && !item.hide) {
          item = customField.formatFormValue(item, values[key]);
        }
      })
    });
    //保存／提交前要去除塞入的连选日期控件
    let rangePickerIndex = -1;
    custFormValues.map((item, index)=> {
      if (item.messageKey === 'range_picker') {
        rangePickerIndex = index;
      }
    });
    if (rangePickerIndex !== -1 && isClearRange) {
      custFormValues.splice(rangePickerIndex, 1);
    }
    return custFormValues;
  };

  //初始化单据信息
  initInfo = () => {
    const { params } = this.props;
    let info = JSON.parse(JSON.stringify(params.info));
    if(info.sourceApplicationOID){
      info.custFormValues = travelUtil.setDisabledValuesV2(info.custFormValues);
    }
    this.processTravelDate(info, 'edit');
    info.custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    this.copyDefaultCust({data: info},'edit');
    this.setState({info});
  };

  getItineraryHead = () => {
    const { info } = this.props.params;
    if (info.applicationOID) {
      this.setState({loading: true});
      //这里只是用行程头校验单据头日期是否可更改 需要明细，判断差补的时候用
      requestService.getItineraryHead(info.applicationOID, true).then(res => {
        this.setState({itineraryHeadList: res.data, loading: false});
      }).catch(err => {
        this.setState({loading: false});
        errorMessage(err.response);
      });
    }
  };

  checkedChange = (field, value, allValue) => {
    if (field.messageKey === 'select_department') {
      setTimeout(() => {
        //新建默认值的情况下，公司不会触发onChange，部门的onChange需要等成本中心change完成再处理逻辑
        this.checkedChangeNext(field, value, allValue);
      }, 50)
    } else {
      this.checkedChangeNext(field, value, allValue);
    }
  };

  /**
   * 部分表单控件value值变化监听函数
   * @param field 表单项
   * @param value 控件value值（某一个对象的某一个属性值），
   * @param allValue 控件完整值（整个对象或者数组）
   */
  checkedChangeNext = (field,value,allValue) => {
    const { jobInfo, itineraryHeadList, isAlreadyClearBudgetDetail } = this.state;
    let copy = this.state.copyDefaultValues;
    let isChangeCompany = false;
    let isChangeDepartment = false;
    let isChangeFatherCostCenter = false;
    let isChangeCurrency = false;
    let oldCurrencyCode = null;
    let { info, quotaObj } = this.state;
    let custForm = info.custFormValues || [];
    let id = 'formValueOID';
    copy.map(res => {
      if((res.messageKey === field.messageKey) && value !== res.value && (res.fieldOID === field.fieldOID) && (field.messageKey === 'select_cost_center' || field.messageKey === 'select_department')){
        res.showName = allValue;
        res.value = value;
        if (field.messageKey === 'select_cost_center' && field.dataSource && JSON.parse(field.dataSource || '{}').type === 'father') {
          isChangeFatherCostCenter = true;
        }
        if (field.messageKey === 'select_department') {
          isChangeDepartment = true;
        }
      }
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID && field.messageKey === 'select_company') {
        isChangeCompany = true;
        res.value = value;
      }
      if (res.messageKey === field.messageKey && value !== res.value && res.fieldOID === field.fieldOID && field.messageKey === 'currency_code') {
        isChangeCurrency = true;
        oldCurrencyCode = res.value;
        res.value = value;
      }
    });
    //切换了公司，得清空额度里选择的银行卡，切换成不启用额度
    if (isChangeCompany) {
      quotaObj.takeQuota = false;
      quotaObj.quotaBankCardOID = '';
      this.setState({quotaObj});
    }
    //切换了公司.或者切换部门都要查询是否要清空成本中心，切公司额外要看是否清空部门
    if (isChangeCompany || isChangeDepartment) {
      this.setState({loading: true});
      let params = {
        userOID: this.getApplicantOID(),
        departmentOID: '',
        companyOID: '',
        costCenterItemOIDs: []
      };
      custForm.forEach(copyField => {
        if (copyField.messageKey === 'select_department') {
          params.departmentOID = copyField.value;
        }
        if (copyField.messageKey === 'select_company') {
          params.companyOID = copyField.value;
        }
        if (copyField.messageKey === 'select_cost_center' && copyField.value) {
          params.costCenterItemOIDs.push(copyField.value);
        }
      });
      //因为是在onChange中执行的此方法，departmentOID，companyOID不是最新值，要从value中赋值
      if (isChangeCompany) {
        params.companyOID = value;
      }
      if (isChangeDepartment) {
        params.departmentOID = value;
      }
      //如果departmentOID，companyOID没有值，要从岗位信息中赋值
      if (!params.companyOID) {
        params.companyOID = jobInfo.companyOID;
      }

      if (isChangeCompany && params.departmentOID) {
        baseService.checkDepartmentNeedEmpty({companyOID: params.companyOID, departmentOID: params.departmentOID}).then(res => {
          if (res.data && res.data.association === 'N') {
            params.departmentOID = '';
            this.checkCostCenter(params, true, custForm, copy);
          } else {
            this.checkCostCenter(params, false, custForm, copy);
          }
        }).catch(err => {
          this.setState({loading: false});
        });
      } else {
        this.checkCostCenter(params, false, custForm, copy);
      }
    }
    //切换了父成本中心要清空子成本中心项
    if (isChangeFatherCostCenter) {
      let setData = {};
      custForm.map(i => {
        if (i.messageKey === 'select_cost_center' && i.dataSource && JSON.parse(i.dataSource || '{}').type === 'son') {
          setData[i[id]] = undefined;
        }
      });
      this.props.form.setFieldsValue(setData);
      copy.map(item => {
        if (item.messageKey === 'select_cost_center' && item.dataSource && JSON.parse(item.dataSource || '{}').type === 'son') {
          item.showName = undefined;
          item.value = '';
        }
      });
    }

    if (isChangeCurrency && !isAlreadyClearBudgetDetail) {
      //判断是否有预算明细行
      let isHasExpense = requestUtil.isHasBudgetDetail(itineraryHeadList);
      let setDataCurrencyKey = null; //币种控件在values中的key值
      custForm.map(i => {
        if (i.messageKey === 'currency_code') {
          setDataCurrencyKey = i[id];
        }
      });
      if (isHasExpense) {
        //弹框提示是否继续修改币种
        Modal.confirm({
          title: messages('common.info')/*提示*/,
          content: <div>
            <p>{messages('request-1.key825')/*修改币种会清除已填写的明细，是否继续？*/}</p>
          </div>,
          okText: messages('common.ok')/*确定*/,
          cancelText: messages('common.cancel')/*取消*/,
          onOk: () => this.handleChangeCurrency(copy),
          onCancel: () => this.cancelChangeCurrency(copy, setDataCurrencyKey, oldCurrencyCode)
        });
      } else {
        this.setState({copyDefaultValues:copy});
      }
    } else {
      this.setState({copyDefaultValues:copy});
    }
  };

  //确认修改币种
  handleChangeCurrency = (copyValue) => {
    const { info } = this.state;
    this.setState({
      copyDefaultValues: copyValue
    });
    this.setState({loading: true});
    requestService.removeBudgetDetail(info.applicationOID).then(res => {
      this.setState({loading: false, isAlreadyClearBudgetDetail: true});
      sessionStorage.setItem('isNeedApplicationRefresh', 'true');
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  //取消修改币种
  cancelChangeCurrency = (copyValue, setDataKey, oldCurrency) => {
    copyValue.map(item => {
      if (item.messageKey === 'currency_code') {
        item.value = oldCurrency;
      }
    });
    this.setState({copyDefaultValues: copyValue});
    this.props.form.setFieldsValue({[setDataKey]: oldCurrency});
  };

  //切换公司或者部门校验成本中心是否清空
  /**
   *
   * @param params 清空成本中心接口所需参数
   * @param isClearDepartment 是否要清空部门
   * @param custForm 当前控件的custForm
   * @param copy
   */
  checkCostCenter = (params, isClearDepartment, custForm, copy) => {
    const { jobInfo } = this.state;
    let id = this.props.params.applicationOID ? 'formValueOID' : 'fieldOID';
    //切换公司可能清空部门，此时该接口接收的部门参数应该是岗位部门
    if (!params.departmentOID) {
      params.departmentOID = jobInfo.departmentOID;
    }
    requestService.checkCostCenterNeedEmptyV2(params).then(res => {
      //res.data中为false说明是不可见，要清空成本中心项
      if (res.data) {
        let setData = {};
        custForm.map(i => {
          if (i.messageKey === 'select_cost_center' && !res.data[i.value]) {
            setData[i[id]] = undefined;
          }
          if (i.messageKey === 'select_department' && isClearDepartment) {
            setData[i[id]] = undefined;
          }
        });
        this.props.form.setFieldsValue(setData);
        copy.map(item => {
          if (item.messageKey === 'select_cost_center' && !res.data[item.value]) {
            item.showName = undefined;
            item.value = '';
          }
          if (item.messageKey === 'select_department' && isClearDepartment) {
            item.showName = undefined;
            item.value = '';
          }
        });
        this.setState({copyDefaultValues: copy});
      }
    }).finally(() => {
      this.setState({loading: false});
    });
  };

  getApplicantOID = () => {
    const { applicantOID } = this.props.params;
    const { userOID } = this.props.user;
    return (applicantOID && applicantOID !== ':applicantOID') ? applicantOID : userOID;
  };

  //判断是否可以加签
  isCounterSignEnable = () => {
    let params = {
      companyOID: this.props.company.companyOID,
      formOID: this.props.params.formOID,
      counterSignType: 'enableAddSignForSubmitter',
    };
    approveRequestService.postAddSignEnableScope(params).then(res =>{
      if (res.data.enabled) {
        //加签人范围
        this.setState({
          signEnable: res.data.enabled,
          signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs
        });
      }
    });
  };

  /**
   * 备份默认值，做修改参照基准
   * @param res
   * @param status 表单状态 edit create
   */
  copyDefaultCust = (res, status) => {
    let dev = [];
    dev.checkedChange = this.checkedChange;//设置监听
    dev.checkedOk = this.checkedOk;//设置监听 修改日期连选专用
    if(status === 'edit'){
      res.data.custFormValues.map(m => {
        dev.push({
          value: m.value,
          messageKey: m.messageKey,
          formValueOID: m.formValueOID,
          fieldOID: m.fieldOID,
          fieldName:m.fieldName,
          required:m.required,
          showName:{name:m.showValue},
          initValue:{value:m.value,name:m.showValue},
          showValue:m.showValue,
          dataSource:m.dataSource,
          fieldContent: m.fieldContent,
          fieldConstraint: m.fieldConstraint
        });
      });
      this.setState({copyDefaultValues: dev});
    }
  };

  //日期连选控件打开或者关闭的时候的回调
  checkedOk = (field, value) => {
    let info = this.state.info;
    let copy = this.state.copyDefaultValues;
    let startDate = null;
    let endDate = null;
    setTimeout(() => {
      //value为false表示关闭日期弹框
      if (!value && field.value) {
        startDate = field.value.split('\"')[1];
        endDate = field.value.split('\"')[3];
        if (field.enableTime) {
          startDate = moment(startDate).second(0).utc().format();
          endDate = moment(endDate).second(0).utc().format();
        } else {
          startDate = moment(startDate).hours(0).minutes(0).seconds(0).utc().format();
          endDate = moment(endDate).hours(23).minutes(59).seconds(0).utc().format();
        }

        if (this.isSetCloseEnabled) {
          this.closeDate = moment(endDate).add(this.closeDay, 'days');
        }

        //赋值到start_date,end_date控件
        //改日期校验弹框
        this.refreshRangeDate(info.custFormValues, startDate, endDate);
        this.setState({
          info:info
        }, () => {
          this.judgeDateChange(startDate, endDate);
        });
      }
    },500);
  };

  //校验日期是否大于行程头的日期
  judgeDateChange = (startDate, endDate) => {
    const { itineraryHeadList, isAlreadyClearSubsidy } = this.state;
    let copy = this.state.copyDefaultValues;
    if (requestUtil.judgeItineraryDateRange(startDate, endDate, itineraryHeadList)) {
      if (requestUtil.isHasSubsidy(itineraryHeadList) && !isAlreadyClearSubsidy) {
        let fieldStr = messages('request-1.key226')/*出差往返日期*/;
        let message = messages('request-1.key229',{arg1: fieldStr})/*更改{arg1}将清空已添加差补*/;
        Modal.confirm({
          title: messages('request-1.key236')/*警告*/,
          content: <div>
            <p>{message}</p>
          </div>,
          okText: messages('request-1.key420')/*更改*/,
          cancelText: messages('common.cancel')/*取消*/,
          onOk: ()=> {
            this.refreshRangeDate(copy, startDate, endDate);
            this.setState({copyDefaultValues: copy});
            this.clearSubsidy();
          },
          onCancel: ()=> {
            this.cancelDateChange('virtual_range_picker');
          },
        });
      } else {
        this.refreshRangeDate(copy, startDate, endDate);
        this.setState({copyDefaultValues: copy});
      }
    } else {
      this.baseModalDisableDateChange('virtual_range_picker');
    }
  };

  //清空差补
  clearSubsidy = () => {
    travelService.deleteAllSubsidy(this.props.params.applicationOID).then(res => {
      message.success(messages('request-1.key254')/*已清空差补*/);
      this.setState({isAlreadyClearSubsidy: true});
      sessionStorage.setItem('isNeedApplicationRefresh', 'true');
    }).catch(err => {
      errorMessage(err.response);
    });
  };

  //日期校验范围不通过，不允许修改日期
  baseModalDisableDateChange = (currentKey) => {
    Modal.error({
      title: messages('common.info')/*提示*/,
      content: messages('request-1.key421')/*单据日期需包含已保存的行程日期范围，请检查后修改*/,
      okText: messages('common.ok')/*确定*/,
      onOk: ()=> {
        this.cancelDateChange(currentKey);
      }
    });
  };

  //取消日期更改
  cancelDateChange = (currentKey) => {
    let copy = this.state.copyDefaultValues;
    let oldStartDate = null;
    let oldEndDate = null;
    let setData = {};
    copy.map(item => {
      if (item.messageKey === 'start_date') {
        oldStartDate = item.value;
      }
      if (item.messageKey === 'end_date') {
        oldEndDate = item.value;
      }
    });
    if (this.isSetCloseEnabled) {
      this.closeDate = moment(oldEndDate).add(this.closeDay, 'days');
    }

    let info = this.state.info;
    this.refreshRangeDate(info.custFormValues, oldStartDate, oldEndDate);
    info.custFormValues.forEach(custFormValue => {
      if (custFormValue.messageKey === 'range_picker') {
        custFormValue.showValue = [moment(oldStartDate), moment(oldEndDate)];
        setData[currentKey] = [moment(oldStartDate), moment(oldEndDate)];
      }
    });
    this.props.form.setFieldsValue(setData);
    this.setState({info});
  };

  //连选日期变更后刷新date数据
  refreshRangeDate = (values, startDate, endDate) => {
    values.map(res=>{
      if(res.messageKey === 'start_date'){
        res.value = startDate;
      }
      if(res.messageKey === 'end_date'){
        res.value = endDate;
      }
    });
  };

  //处理差旅申请单，费用申请单的日期连选
  //type 新建create 编辑edit
  processTravelDate = (applicationData, type) => {
    if (applicationData.formType === 2001 || applicationData.formType === 2002) {
      let startDateFieldName = '';
      let endDateFieldName = '';
      let startDateRequired = false;
      let endDateRequired = false;
      let keyName = type === 'create' ? 'customFormFields' : 'custFormValues';
      applicationData[keyName].map((field) => {
        if (field.messageKey === 'start_date') {
          startDateFieldName = field.fieldName;
          startDateRequired = field.required;
        }
        if (field.messageKey === 'end_date') {
          endDateFieldName = field.fieldName;
          endDateRequired = field.required;
        }
      });
      let rangePicker = {
        messageKey: 'range_picker',
        fieldOID: travelUtil.generateUid(),
        fieldName: `${startDateFieldName} - ${endDateFieldName}`,
        promptInfoList: [startDateFieldName, endDateFieldName],
        fieldType: 'TEXT',
        disabledDate: current => this.disabledDate(current),
        enableTime: false,
        defaultValueTime: [], //启用时间的默认值
        required: applicationData.formType === 2001 ? true : startDateRequired && endDateRequired,
        sequence: null,
        hide: null,
        value: null
      };
      let hasStartEndDate = 0;
      let startDate = null;
      let endDate = null;
      let enableStartDateTime = false; //开始日期启用时间
      let enableEndDateTime = false; //结束日期启用时间
      if (type === 'edit') {
        applicationData.custFormValues.map((field) => {
          if (field.messageKey === 'start_date') {
            rangePicker.sequence = field.sequence;
            rangePicker.hide = field.hide;
            startDate = field.value;
            enableStartDateTime = requestUtil.processEnableTime(field);
            hasStartEndDate++;
          }
          if (field.messageKey === 'end_date') {
            endDate = field.value;
            enableEndDateTime = requestUtil.processEnableTime(field);
            hasStartEndDate++;
          }
        });
        if (hasStartEndDate === 2) {
          if (enableStartDateTime && enableEndDateTime) {
            rangePicker.enableTime = true;
          }
          rangePicker.formValueOID = 'virtual_range_picker';
          rangePicker.showValue = [moment(startDate), moment(endDate)];
          applicationData.custFormValues.push(rangePicker);
          this.setState({isShowRangePicker: true}, () => {
            this.processDisableTime(applicationData, type);
          });
        }
      }
    }
  };

  //处理日期连选控件的禁用日期
  disabledDate = (current) => {
    const { newProfile } = this.props;
    let floatDays = newProfile['applicationControlOpt']['floatDays'];
    //floatDays有四种情况：空，0，正数，负数
    if (typeof floatDays === 'number') {
      let point = moment().add(floatDays, 'days');
      return moment(current).isBefore(point, 'day');
    } else {
      return false;
    }
  };

  //处理是否停用日期
  //type 新建create 编辑edit
  processDisableTime = (applicationData, type) => {
    //新建时的处理
    if (applicationData.customFormProperties.enabled === 1 && type === 'create') {  //是否和停用启用有关
      this.isSetCloseEnabled = true;
      this.closeDay = applicationData.customFormProperties.closeDay;
      let date = new Date();
      this.closeDate = moment(date).add(this.closeDay, 'days');
    }
    //编辑时的处理
    if (applicationData.closeEnabled && type === 'edit') {
      this.isSetCloseEnabled = true;
      this.closeDay = applicationData.customFormProperties.closeDay;
      if (applicationData.closeDate) {
        this.closeDate = moment(applicationData.closeDate);
      }
    }
  };

  goBack = (value) => {
    const { close } = this.props;
    if (close) {
      close(value);
    }
  };

  //根据表单信息渲染控件
  renderCustom = (field, index) => {
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { formDefaultValue, isShowRangePicker, formInfo, copyDefaultValues, jobId, jobInfo, info } = this.state;
    //label
    let label = field.fieldName;
    if (field.messageKey === 'number') {
      label = `${field.fieldName}${JSON.parse(field.fieldContent || '{}').unit && `(${JSON.parse(field.fieldContent || '{}').unit})`}`;
    }

    //rules
    let maxLength = travelUtil.getMaxLength(field);
    let rules = [{
      required: field.required,
      message: messages('common.can.not.be.empty',{arg1: field.fieldName})/*{arg1} 不能为空*/
    }];
    maxLength && rules.push({
      max: maxLength,
      message: messages('common.max.characters.length',{arg1: maxLength})/*最多输入{arg1}个字符*/
    });
    (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
      validator: (rule, value, callback) => {
        let emptyItem = '';
        value && value.map(item => {
          if (!item.name) {
            emptyItem = messages('request-1.key157')/*姓名*/;
            return
          }
          if (!item.certificateNo) {
            emptyItem = messages('request-1.key158')/*证件号*/
          }
        });
        if (!emptyItem) {
          callback();
          return
        }
        callback(messages('common.can.not.be.empty',{arg1: emptyItem})/*{arg1} 不能为空*/)
      }
    });

    let formDetailValues = formInfo;
    formDetailValues.currencyCode = info.currencyCode;
    formDetailValues.applicantOID = info.applicant && info.applicant.userOID;
    formDetailValues.customFormFields = info.custFormValues;

    return (
      <div key={index}>
        {/*展示连选日期时，不展示开始日期，结束日期*/}
        {/*新版差旅申请单没有预算明细控件*/}
        {/*内部参与人控件配了不启用isUse为false，则不展示*/}
        {(!isShowRangePicker || (field.messageKey !== 'start_date' && field.messageKey !== 'end_date')) && travelUtil.isShowParticipant(field) && (
          <FormItem {...formItemLayout} label={label || ' '} key={field.formValueOID} colon={!!label}>
            {((field.messageKey === 'total_budget' && formInfo.formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
            {getFieldDecorator(field.formValueOID, {
              rules,
              valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
              initialValue: customField.getInitialValue(field)
            })(
              customField.renderForm({
                field,
                formDetail: formDetailValues,
                copyValue: copyDefaultValues,
                formValues: getFieldsValue(),
                jobId,
                jobInfo,
                propsParams: {
                  departmentOID: jobInfo.departmentOID,
                  companyOID: jobInfo.companyOID,
                  setOfBooksId: formInfo.fromType === 3 ? info.setOfBooksId : undefined
                },
                form: this.props.form,
                formKey: 'formValueOID'
              })
            )}
          </FormItem>
        )}
        {/*差旅连选日期，预计停用日期的控件*/}
        {isShowRangePicker && this.isSetCloseEnabled && field.messageKey === 'range_picker' && (
          <FormItem {...formItemLayout} label={messages('request-1.key4')/*预计关闭日期*/}>
            <DatePicker disabled={true} value={this.closeDate} format="YYYY-MM-DD" style={{width: '100%'}}/>
          </FormItem>
        )}
      </div>
    )
  };

  //提交前检查组合控件的表单值验证,异步方法
  submitSaveValidateCombinationForm(){
    let isEdit = !!this.props.params.applicationOID;
    let customFormFields = isEdit ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let isHaveValidate = false;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if(~needValidateForms.indexOf(item.messageKey)){
        let info = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
        if(info){
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({[!isEdit ? item.fieldOID : item.formValueOID]:info});
          isHaveValidate = true;
        }
      }
    });
    return isHaveValidate;
  };

  //组合表单验证结果
  combinationFormValidateResult(){
    let isEdit = !!this.props.params.applicationOID;
    let customFormFields = isEdit ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let isPassValid = true;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if(~needValidateForms.indexOf(item.messageKey)){
        let info = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
        if(info){
          isPassValid = isPassValid && info.isPassValid;
        }
      }
    });
    return isPassValid;
  };

  //保存&提交前验证custFormValues
  custFormValuesValidate = (custFormValues) => {
    const {formType, editTicketInfoVisible} = this.state;
    let isOk = true;
    //校验开始日期是否小于结束日期
    let startDateValue = null;
    let endDateValue = null;
    custFormValues.map(item => {
      if (item.messageKey === 'start_date') {
        startDateValue = item.value;
      }
      if (item.messageKey === 'end_date') {
        endDateValue = item.value;
      }
      //item.value是string类型
      //999999999999999.9999999999 >= 1000000000000000 是true
      if (item.messageKey === 'calculate_formula' && item.value && item.value.split('.')[0].length >= 16 && isOk) {
        message.error(messages('request-1.key242',{arg1: item.fieldName})/*{arg1}最多支持15位数字*/);
        isOk = false;
      }
    });
    if (startDateValue && endDateValue && moment(startDateValue).isAfter(endDateValue)) {
      message.error(messages('request-1.key243')/*开始时间不能晚于结束时间*/);//开始时间不能晚于结束时间
      isOk = false;
    }
    return isOk;
  };

  //保存／提交前处理单据数据
  processValues = (params) => {
    const { user } = this.props;
    const { jobId } = this.state;
    //新建的时候的特殊处理
    if (!this.props.params.applicationOID) {
      params.remark = ''; //新建时要把表单带出的remark清空，这不是单据的remark
      params.applicantOID = user.userOID; //新建时要把applicantOID填上，现在customValues里去除了申请人控件
      params.jobId = jobId; //新建的时候要赋值单据岗位id
    }
    if(this.isSetCloseEnabled){//设置自动停用日期
      params.closeEnabled = 1;
      params.closeDate = this.closeDate;
    }
    //如果内部参与人控件配置了隐藏，则把内部参与人赋值为申请人
    params.custFormValues && params.custFormValues.map(valueItem => {
      if (valueItem.messageKey === 'select_participant' && valueItem.hide) {
        valueItem.value = JSON.stringify([{
          userOID: user.userOID,
          fullName: user.fullName,
          participantOID: user.userOID,
          avatar: user.avatar
        }]);
      }
    });
  };

  processQuotaValues = (params) => {
    const { quotaObj } = this.state;
    params.takeQuota = quotaObj.takeQuota;
    params.quotaCurrencyCode = quotaObj.takeQuota ? quotaObj.quotaCurrencyCode : '';
    params.quotaAmount = quotaObj.quotaAmount;
    params.quotaBankCardOID = quotaObj.takeQuota ? quotaObj.quotaBankCardOID : '';
  };

  handleSave = () => {
    if (this.submitSaveValidateCombinationForm()) {
      //组合子表单验证信息传递需要时间
      setTimeout(() => this.delayHandleSave(), 10);
    } else {
      this.delayHandleSave();
    }
  };

  //处理保存
  delayHandleSave = (isGoAutoLoan) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!this.combinationFormValidateResult()) {
        return;
      }
      if (!err) {
        const { info } = this.state;
        let params = JSON.parse(JSON.stringify(info));
        params.custFormValues = this.getCustFormValues(values, true);
        if(!this.custFormValuesValidate(params.custFormValues)){
          return;
        }
        params.applicant = null;
        this.processQuotaValues(params);
        if (values.addSign) {
          params.countersignApproverOIDs = values.addSign;
        }
        this.processValues(params);
        this.judgeDisableDate(params);
      }
    });
  };

  //保存时校验停用日期是否早于当前时间
  judgeDisableDate = (params) => {
    if (this.isSetCloseEnabled && this.closeDate) {
      let date = new Date();
      date = moment(date).format('YYYY-MM-DD');
      let disableDate = moment(this.closeDate).format('YYYY-MM-DD');
      if (moment(disableDate).isBefore(date)) {
        //弹框提示是否继续提交
        Modal.confirm({
          title: messages('request-1.key244')/*关闭时间早于当前时间*/,
          content: <div>
            <p>{messages('request-1.key245')/*您仍可以提交，但审批通过后，不可报销*/}</p>
          </div>,
          okText: messages('common.submit')/*提交*/,
          cancelText: messages('request-1.key133')/*返回修改*/,
          onOk: () => this.handleSaveStep1(params),
          onCancel: () => {},
        });
      } else {
        this.handleSaveStep1(params);
      }
    } else {
      this.handleSaveStep1(params);
    }
  };

  handleSaveStep1 = (params) => {
    const { formInfo } = this.state;
    this.setState({saveLoading: true});
    let partiOid = "";
    let indexOf = 0;
    let formVs = params.custFormValues;
    let currentStatus = this.props.params.applicationOID ? 'edit' : 'create';

    formVs.map((cus, index) => {//通过messageKey拿到对应表单的key，applicationOID存在为编辑状态
      if (cus.messageKey === "select_participant") {
        partiOid = this.props.params.applicationOID ? cus.formValueOID : cus.fieldOID;
        indexOf = index;
      }
    });
    let isSetSelectParticipant = false;//是否配置了参与人字段，如果配置了且是开启内部参与人，则需要校验
    params.custFormValues.map(item =>{
      if(item.messageKey === 'select_participant'){
        isSetSelectParticipant = true;
        if (item.fieldContent) {
          isSetSelectParticipant = JSON.parse(item.fieldContent).isUse;
        }
        //内部参与人不必填的时候，没选内部参与人员就不需要进行权限校验了
        let parts = JSON.parse(item.value ? item.value : '[]');
        if (!parts.length) {
          isSetSelectParticipant = false;
        }
      }
    });
    if(isSetSelectParticipant){
      this.setState({loading: true});
      travelService.travelValidate(params,this.props.language, formInfo).then(res => {//参与人权限校验
        let partis = this.props.form.getFieldValue(partiOid);
        let showName = "";
        res.data.map(item => {
          if (item.errorDetail) {
            showName = `${showName} ${item.fullName}`;
          }
        });
        if (showName) {
          //弹框提示是否删除不在权限内的参与人
          Modal.confirm({
            title: messages('common.info')/*提示*/,
            content: <div>
              <p>{messages('request-1.key249',{arg1: showName})/*{arg1} 不在可选人员范围内，是否删除以上人员?*/}</p>
            </div>,
            okText: messages('common.delete')/*删除*/,
            cancelText: messages('common.cancel')/*取消*/,
            onOk: ()=> this.deletePartis(res, partis),
            onCancel: () => {this.setState({saveLoading: false, loading: false});}
          });
        } else {
          this.travelParams = params;
          this.cancelDelPartis(params, 'save', currentStatus);//如果参与人员都符合权限，不弹框默认走取消弹框函数。
        }
      }).catch(err => {
        this.setState({saveLoading: false, loading: false});
        let error = err.response.data;
        if (error.validationErrors && error.validationErrors.length) {
          if(error.validationErrors[0].externalPropertyName){
            switch (error.validationErrors[0].externalPropertyName) {
              case '2010': //申请人为空
                message.error(messages('request-1.key111')/*申请人为空.*/);
                break;
              case '2011': //部门为空
                message.error(messages('request-1.key112')/*部门为空.*/);
                break;
              case '2012': //成本中心为空
                message.error(messages('request-1.key113')/*成本中心为空.*/);
                break;
              default: message.error(messages('request-1.key114')/*出错了，请联系管理员*/);
            }
          }
        } else {
          message.error(`${messages('common.save.filed')/*保存失败*/}，${error.message}`)
        }
      })
    }else{
      this.travelParams = params;
      this.cancelDelPartis(params, 'save', currentStatus);
    }
  };

  /**
   * 保存和提交的流程
   * @param params 保存和提交的结构体数值
   * @param type   区分保存(save)还是提交(submit)动作
   * @param status 区分是新建（create）还是编辑（edit）
   */
  cancelDelPartis = (params, type, status) => {
    this.setState({loading: true});
    if (type === 'save') {//保存走这里
      if (status === 'create') {
        params.travelApplication = {};
        //设置行程管控
        params.travelApplication.manageType = params['customFormPropertyMap']['application.property.manage.type'];
      }
      travelService.saveTravelRequest(params).then(res => {
        this.setState({loading: false, saveLoading: false});
        message.success(messages('request-1.key251')/*已保存*/);
        sessionStorage.setItem('isNeedApplicationRefresh', 'true');
        this.goBack(true);
      }).catch(err => {
        this.setState({loading: false, saveLoading: false});
        message.error(messages('request-1.key252')/*操作失败:*/  + `${err.response.data.message}`);
      });
    }
  };

  //删除不在权限内的参与人
  deletePartis = (res, partis) => {
    res.data.map(item => {
      if (item.errorDetail) {
        partis && partis.map((p, ind) => {
          if (p.userOID === item.userOID) {
            partis.splice(ind, 1);
          }
        })
      }
    });
    this.setState({
      saveLoading: false,
      loading: false
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, saveLoading, formInfo, info, signEnable, signCompanyOIDs } = this.state;
    const defaultValues = info.custFormValues || [];
    let signPerson = [];
    info.countersignApproverNames && info.countersignApproverNames.forEach(item => {
      signPerson.push({userOID: item.userOID, fullName: item.fullName});
    });
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);
    let chooserItem = deepFullCopy(chooserData['user']);
    chooserItem.title = messages('request-1.key268')/*自选审批人*/;
    if(signCompanyOIDs.length > 0){
      chooserItem.url = `/api/users/v3/search?corporationOID=${signCompanyOIDs}&companyOID=${signCompanyOIDs}`;
    }
    return (
      <div>
        <WaterMark/>
        <Spin spinning={loading}>
          <Form>
            <div style={{margin: '0 0 20px 30%'}}>{customField.instructionsTag(formInfo.customFormPropertyMap)}</div>
            {defaultValues.map((field, index) => {
              return this.renderCustom(field, index)
            })}
            {signEnable && (
              <FormItem {...formItemLayout} label={signName} key="addSign">
                {getFieldDecorator('addSign', {
                  rules: [{
                    required: formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.enableCounterSignForSubmitterMustWriter === 'true',
                    message: messages('common.can.not.be.empty',{arg1: signName})/*{arg1} 不能为空*/
                  }],
                  initialValue: signPerson
                })(
                  <Chooser
                    selectorItem={chooserItem}
                    valueKey="userOID"
                    labelKey="fullName"
                    onlyNeed="userOID"
                    maxNum={26}
                    listExtraParams={{roleType: 'TENANT'}}
                    showArrow={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.countersignType === '2'}
                    newline
                  />
                )}
              </FormItem>
            )}
          </Form>
        </Spin>
        <div className="slide-footer">
          <Button loading={saveLoading} type="primary" onClick={this.handleSave}>
            {messages('common.save')/*保存*/}
          </Button>
          <Button onClick={this.goBack}>
            {messages('common.back')/*返回*/}
          </Button>
        </div>
      </div>
    )
  }
}

RequestEditContent.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser,
    newProfile: state.login.options,
  }
}

const wrappedRequestEditContent = Form.create()(RequestEditContent);

export default connect(mapStateToProps)(wrappedRequestEditContent)
